package com.berje.vkalarm.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.berje.vkalarm.IOnDownloadClickListener;
import com.berje.vkalarm.R;
import com.berje.vkalarm.Utils;
import com.berje.vkalarm.VkAlarmMainActivity;
import com.berje.vkalarm.vksdk.KException;
import com.berje.vkalarm.vksdk.model.Audio;
import com.berje.vkalarm.vksdk.model.Group;
import com.berje.vkalarm.vksdk.model.GroupAudioFeed;
import com.berje.vkalarm.vksdk.model.GroupAudioNewsItem;

public class DownloadFragment extends Fragment {
	
	private static final String TAG = "DownloadFragment";

	private GroupWheelAdapter groupWheelAdapter;
	private WheelView groupWheel;

	private List<Group> groups;

	private ListView audioPostListView;

	private TextView postDate;
	private TextView postIndex;

	private Button rewindButton;
	private Button forwardButton;
	private Button downloadButton;
	private ProgressBar progressBar;

	private IOnDownloadClickListener mCallback;

	public DownloadFragment(List<Group> groups) {
		this.groups = groups;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mCallback = (IOnDownloadClickListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement IOnDownloadClickListener");
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate  savedInstanceState: " + savedInstanceState);
		audioPostAdapter = new AudioPostAdapter(getActivity(), R.id.audio_post_listview, new ArrayList<Audio>());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.d(TAG, "onCreateView savedInstanceState: " + savedInstanceState);
		View view = inflater.inflate(R.layout.fragment_download, container, false);

		progressBar = (ProgressBar) view.findViewById(R.id.progress);

		groupWheel = (WheelView) view.findViewById(R.id.groupWheel);
		groupWheel.setVisibleItems(3);

		postDate = (TextView) view.findViewById(R.id.post_date);
		postIndex = (TextView) view.findViewById(R.id.posts_index_text);
		audioPostListView = (ListView) view.findViewById(R.id.audio_post_listview);
		audioPostListView.setAdapter(audioPostAdapter);

		downloadButton = (Button) view.findViewById(R.id.downloadButton);
		downloadButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onDownload();
			}

		});

		rewindButton = (Button) view.findViewById(R.id.rewindButton);
		rewindButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onRewindButton();
			}

		});
		forwardButton = (Button) view.findViewById(R.id.forwardButton);
		forwardButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onForwardButton();
			}

		});
		
		if (groups != null) {
			onGroups(groups);
		}
		
		return view;
	}

	private class GroupWheelAdapter extends AbstractWheelTextAdapter {

		private List<Group> groups;

		private Map<String, Bitmap> bitmapCash = new HashMap<String, Bitmap>();

		public void clearCash() {
			bitmapCash.clear();
		}

		protected GroupWheelAdapter(Context context) {
			super(context, R.layout.spinner_item, NO_RESOURCE);
			setItemTextResource(R.id.spinner_item_text);
		}

		public GroupWheelAdapter(Context context, List<Group> groups) {
			super(context, R.layout.spinner_item, NO_RESOURCE);
			this.groups = groups;
		}

		@Override
		public View getItem(int position, View convertView, ViewGroup parent) {
			View row = super.getItem(position, convertView, parent);
			Group g = groups.get(position);
			((TextView) row.findViewById(R.id.spinner_item_text)).setText(g.getName());
			final ImageView imageView = (ImageView) row.findViewById(R.id.spinner_item_image);
			Bitmap b = g.getPhotoBitmap();
			if (b != null)
				imageView.setImageBitmap(b);
			else
				new AsyncTask<Group, Void, Bitmap>() {

					@Override
					protected Bitmap doInBackground(Group... params) {
						Group g = params[0];
						return Utils.getGroupBitmap(g);
					}

					@Override
					protected void onPostExecute(Bitmap b) {
						super.onPostExecute(b);
						imageView.setImageBitmap(b);
					}

				}.execute(g);

			return row;
		}

		@Override
		public int getItemsCount() {
			if (groups == null)
				return 0;

			return groups.size();
		}

		@Override
		protected CharSequence getItemText(int index) {
			if (groups == null)
				return null;
			return groups.get(index).getName();
		}
	}

	private AudioPostAdapter audioPostAdapter;

	private static SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd.MM yyyy");

	private List<GroupAudioNewsItem> audioPosts;

	private void setAudioPosts(List<GroupAudioNewsItem> items) {
		this.audioPosts = items;
		if (items != null && items.size() > 0) {
			setCurrentAudioPostIndex(0);
		}
	}

	private void onRewindButton() {
		Log.d(TAG, "onRewindButton " + currentAudioPostIndex);
		setCurrentAudioPostIndex(--currentAudioPostIndex);
	}

	private void onForwardButton() {
		Log.d(TAG, "onForwardButton " + currentAudioPostIndex);
		setCurrentAudioPostIndex(++currentAudioPostIndex);
	}

	private void onDownload() {
		Log.d(TAG, "onDownload()");
		mCallback.onDownloadClick();

	}

	private int currentAudioPostIndex = 0;

	private void setCurrentAudioPostIndex(int index) {
		Log.d(TAG, "setCurrentAudioPostIndex(" + index + ")");

		if (audioPosts == null || audioPosts.size() == 0)
			return;

		int size = audioPosts.size();
		Log.d(TAG, "size: " + size);

		if (index < 0 || index >= size) {
			return;
		}

		this.currentAudioPostIndex = index;

		boolean b = index != 0;
		if (b != rewindButton.isEnabled()) {
			rewindButton.setEnabled(b);
		}

		b = index != size - 1;
		if (b != forwardButton.isEnabled()) {
			forwardButton.setEnabled(b);
		}

		postIndex.setText((index + 1) + "(" + size + ")");
		setAudioPost(audioPosts.get(index));
	}

	public void setAudioPost(GroupAudioNewsItem item) {
		if (item == null) {
			postDate.setText("");
			postIndex.setText("");
			audioPostAdapter.clear();
			if (downloadButton.isEnabled())
				downloadButton.setEnabled(false);
			return;
		}

		if (item.getDate() != 0) {
			Date date = new Date(item.getDate() * 1000);
			postDate.setText(sdf.format(date));
		}

		audioPostAdapter.clear();
		if (item.getAudios() != null) {
			boolean b = item.getAudios().size() > 0;

			if (b != downloadButton.isEnabled())
				downloadButton.setEnabled(b);

			for (Audio a : item.getAudios()) {
				audioPostAdapter.add(a);
			}
		}
		audioPostAdapter.notifyDataSetChanged();
	}

	public static class AudioPostAdapter extends ArrayAdapter<Audio> {
		public AudioPostAdapter(Context context, int textViewResourceId, List<Audio> audios) {
			super(context, textViewResourceId, audios);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row;
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = inflater.inflate(R.layout.audio_item, null);
			} else {
				row = convertView;
			}

			try {
				Audio a = getItem(position);

				((TextView) row.findViewById(R.id.audio_item_artist)).setText(a.getArtist());
				((TextView) row.findViewById(R.id.audio_item_title)).setText(a.getTitle());
				long d = a.getDuration();
				((TextView) row.findViewById(R.id.audio_item_duration)).setText(String.format("%d:%02d", d / 60, d % 60));

			} catch (Exception e) {
				Log.e(TAG, "error", e);
			}
			return row;
		}
	}

	private void updateGroupMusicPosts() {
		if (rewindButton.isEnabled())
			rewindButton.setEnabled(false);
		if (forwardButton.isEnabled())
			forwardButton.setEnabled(false);
		if (downloadButton.isEnabled())
			downloadButton.setEnabled(false);
		postIndex.setText("");
		postDate.setText("");
		audioPostAdapter.clear();
		audioPostAdapter.notifyDataSetChanged();
		
		if (groups == null)
			return;

		Group group = groups.get(groupWheel.getCurrentItem());
		long lgid = group.getGid();
		if (lgid == 0)
			return;

		String gid = "g" + lgid;
		new AsyncTask<String, Void, List<GroupAudioNewsItem>>() {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				progressBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected List<GroupAudioNewsItem> doInBackground(String... params) {
				String gid = params[0];
				List<GroupAudioNewsItem> ret = null;
				try {
					GroupAudioFeed gmf = ((VkAlarmMainActivity) getActivity()).getApi().getGroupMusicNews(gid, -1, 0, -1, "", "");
					ret = gmf.getItems();
					// List<GroupAudioNewsItem> items = gmf.getItems();
					// for (GroupAudioNewsItem item : items) {
					// List<Audio> audios = item.getAudios();
					// if (audios != null && audios.size() > 0) {
					// return item;
					// }
					// }

				} catch (KException ke) {
					Log.e(TAG, "KException on getGroupMusicNews");
					mCallback.onVkResponseError(ke);
				} catch (Exception e) {
					Log.e(TAG, "Exception getting feed", e);
				}
				return ret;
			}

			@Override
			protected void onPostExecute(List<GroupAudioNewsItem> items) {
				super.onPostExecute(items);
				setAudioPosts(items);
				progressBar.setVisibility(View.GONE);
			}
		}.execute(gid);
	}

	@Override
	public void onDestroy() {
		Log.d(TAG, "onDestroy()");
		super.onDestroy();
		if (groupWheelAdapter != null)
			groupWheelAdapter.clearCash();

	}

	public List<GroupAudioNewsItem> getAudioPosts() {
		return audioPosts;
	}

	public int getCurrentAudioPostIndex() {
		return currentAudioPostIndex;
	}

	public Group getCurrentGroup() {
		return groups.get(groupWheel.getCurrentItem());
	}

	private boolean gScrolling = false;

	public void onGroups(List<Group> groups) {
		Log.d(TAG, "DownloadFragment.onGroups groups: " + groups);
		if (groups == null)
			return;
		
		this.groups = groups;
		
		groupWheelAdapter = new GroupWheelAdapter(getActivity(), groups);
		groupWheel.setViewAdapter(groupWheelAdapter);
		groupWheel.setCurrentItem(groups.size() / 2);
		updateGroupMusicPosts();
		groupWheel.setVisibility(View.VISIBLE);

		groupWheel.addChangingListener(new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				Log.d(TAG, "groupWheel.onChanged  cItem: " + groupWheel.getCurrentItem() + " scrolling: " + gScrolling);
				if (!gScrolling) {
					updateGroupMusicPosts();
				}
			}
		});

		groupWheel.addScrollingListener(new OnWheelScrollListener() {
			public void onScrollingStarted(WheelView wheel) {
				Log.d(TAG, "groupWheel.onScrollingStarted ");
				gScrolling = true;
			}

			public void onScrollingFinished(WheelView wheel) {
				Log.d(TAG, "groupWheel.onScrollingFinished cItem: " + groupWheel.getCurrentItem());
				gScrolling = false;
				updateGroupMusicPosts();
				// updateCities(city, cities, country.getCurrentItem());
			}
		});
	}
	
}
